package com.suep.data_analysis.controller;

import com.suep.data_analysis.dto.UserConfigDetailDto;
import com.suep.data_analysis.dto.UserConfigListDto;
import com.suep.data_analysis.model.UserConfig;
import com.suep.data_analysis.repository.UserConfigRepository;
import com.suep.data_analysis.service.UserConfigService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.ExampleObject;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import lombok.AllArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@CrossOrigin
@AllArgsConstructor
@RestController
@RequestMapping("api/user-configs")
public class UserConfigController {
    private final UserConfigService userConfigService;
    private final UserConfigRepository userConfigRepository;

    @Operation(
            summary = "获取用户的配置列表",
            description = "根据用户ID查询其所有配置的基本信息（配置ID、用户ID、角色ID、音擎ID），支持关键词搜索和排序",
            parameters = {
                    @Parameter(name = "userId", description = "用户唯一标识", required = true,
                            examples = @ExampleObject(value = "user123", description = "用户ID示例")),
                    @Parameter(name = "keyword", description = "搜索关键词（可选）", required = false,
                            examples = @ExampleObject(value = "仪玄", description = "角色名称搜索示例")),
                    @Parameter(name = "sortBy", description = "排序字段（可选）", required = false,
                            examples = @ExampleObject(value = "createTime", description = "排序字段示例")),
                    @Parameter(name = "sortOrder", description = "排序方式（可选，asc/desc）", required = false,
                            examples = @ExampleObject(value = "desc", description = "排序方式示例"))
            },
            responses = {
                    @ApiResponse(responseCode = "200", description = "成功获取配置列表",
                            content = @Content(mediaType = "application/json",
                                    schema = @io.swagger.v3.oas.annotations.media.Schema(implementation = UserConfigListDto.class))),
                    @ApiResponse(responseCode = "400", description = "用户ID为空", content = @Content)
            }
    )
    @GetMapping
    public ResponseEntity<List<UserConfigListDto>> getUserConfigs(
            @RequestParam String userId,
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false, defaultValue = "createTime") String sortBy,
            @RequestParam(required = false, defaultValue = "desc") String sortOrder
    ) {
        // 简单参数校验
        if (userId == null || userId.trim().isEmpty()) {
            return ResponseEntity.badRequest().build();
        }

        List<UserConfigListDto> configs = userConfigService.getUserConfigsByUserId(userId, keyword, sortBy, sortOrder);
        return ResponseEntity.ok(configs);
    }

    @Operation(
            summary = "获取配置详情",
            description = "根据配置ID查询完整信息（含角色、音擎、驱动盘和技能详情）",
            parameters = {
                    @Parameter(name = "configId", description = "配置唯一标识", required = true,
                            examples = @ExampleObject(value = "cfg-123", description = "配置ID示例")),
                    @Parameter(name = "userId", description = "用户唯一标识", required = true,
                            examples = @ExampleObject(value = "user123", description = "用户ID示例"))
            },
            responses = {
                    @ApiResponse(responseCode = "200", description = "成功获取配置详情",
                            content = @Content(mediaType = "application/json",
                                    schema = @io.swagger.v3.oas.annotations.media.Schema(implementation = UserConfigDetailDto.class))),
                    @ApiResponse(responseCode = "404", description = "配置不存在", content = @Content)
            }
    )
    @GetMapping("/{configId}")
    public ResponseEntity<UserConfigDetailDto> getConfigDetail(
            @PathVariable String configId,
            @RequestParam String userId
    ) {
        // 简单参数校验
        if (userId == null || userId.trim().isEmpty()) {
            return ResponseEntity.badRequest().build();
        }

        UserConfigDetailDto detail = userConfigService.getConfigDetailById(configId);
        if (detail == null || !detail.getUserId().equals(userId)) {
            return ResponseEntity.notFound().build();
        }

        return ResponseEntity.ok(detail);
    }

    @Operation(
            summary = "保存用户配置",
            description = "创建或更新用户配置（自动关联当前用户ID）",
            parameters = {
                    @Parameter(name = "userId", description = "用户唯一标识", required = true,
                            examples = @ExampleObject(value = "user123", description = "用户ID示例"))
            },
            responses = {
                    @ApiResponse(responseCode = "200", description = "成功保存配置",
                            content = @Content(mediaType = "application/json",
                                    schema = @io.swagger.v3.oas.annotations.media.Schema(implementation = UserConfigDetailDto.class))),
                    @ApiResponse(responseCode = "400", description = "无效的配置数据", content = @Content)
            }
    )
    @PostMapping
    public ResponseEntity<UserConfigDetailDto> saveUserConfig(
            @RequestBody UserConfig config,
            @RequestParam String userId
    ) {
        // 强制设置用户ID（防止前端篡改）
        config.setUserId(userId);

        UserConfigDetailDto savedConfig = userConfigService.saveUserConfig(config);
        return ResponseEntity.ok(savedConfig);
    }

    @Operation(
            summary = "删除用户配置",
            description = "根据配置ID删除用户配置",
            parameters = {
                    @Parameter(name = "configId", description = "配置唯一标识", required = true,
                            examples = @ExampleObject(value = "cfg-123", description = "配置ID示例")),
                    @Parameter(name = "userId", description = "用户唯一标识", required = true,
                            examples = @ExampleObject(value = "user123", description = "用户ID示例"))
            },
            responses = {
                    @ApiResponse(responseCode = "204", description = "配置已成功删除", content = @Content),
                    @ApiResponse(responseCode = "404", description = "配置不存在", content = @Content)
            }
    )
    @DeleteMapping("/{configId}")
    public ResponseEntity<Void> deleteUserConfig(
            @PathVariable String configId,
            @RequestParam String userId
    ) {
        // 先验证配置是否属于该用户
        UserConfig config = userConfigRepository.selectById(configId);
        if (config == null || !config.getUserId().equals(userId)) {
            return ResponseEntity.notFound().build();
        }

        userConfigService.deleteUserConfig(configId);
        return ResponseEntity.noContent().build();
    }
}